<template>
  <div class="ai-guide-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-8">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-2">
              AI 智能攻略
            </h1>
            <p class="text-gray-600 dark:text-gray-400">
              让 AI 为您定制专属贵港旅游攻略，打造完美行程
            </p>
          </div>
          <el-button
            class="back-btn"
            type="primary"
            plain
            @click="router.push('/guides')"
          >
            <el-icon class="mr-1"><Back /></el-icon>
            返回攻略
          </el-button>
        </div>
      </div>
    </div>

    <div class="container mx-auto px-4 py-8">
      <!-- API状态提示 -->
      <div v-if="apiStatus.checked" :class="[
        'mb-6 p-4 rounded-lg flex items-center',
        apiStatus.available ? 'bg-green-50 text-green-800 border border-green-200' : 'bg-yellow-50 text-yellow-800 border border-yellow-200'
      ]">
        <el-icon :class="['mr-3 text-xl', apiStatus.available ? 'text-green-500' : 'text-yellow-500']">
          <component :is="apiStatus.available ? 'Check' : 'Warning'" />
        </el-icon>
        <div>
          <div class="font-medium">{{ apiStatus.available ? 'AI服务连接正常' : 'AI服务连接异常' }}</div>
          <div class="text-sm">
            {{ apiStatus.available ? '您的攻略将由DeepSeek AI智能生成' : '将使用本地模板生成攻略，可能无法提供个性化内容' }}
          </div>
        </div>
      </div>
      
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧表单区域 -->
        <div class="flex-1">
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-8">
            <el-form
              ref="formRef"
              :model="form"
              :rules="rules"
              label-position="top"
              class="space-y-6"
            >
              <!-- 基本信息 -->
              <div class="form-section">
                <h2
                  class="text-xl font-medium text-gray-900 dark:text-white mb-6 flex items-center"
                >
                  <el-icon class="mr-2"><InfoFilled /></el-icon>
                  基本信息
                </h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <!-- 游玩天数 -->
                  <el-form-item label="游玩天数" prop="days">
                    <el-input-number
                      v-model="form.days"
                      :min="1"
                      :max="7"
                      class="!w-full"
                    />
                  </el-form-item>

                  <!-- 出行时间 -->
                  <el-form-item label="出行时间" prop="date">
                    <el-date-picker
                      v-model="form.date"
                      type="date"
                      placeholder="选择日期"
                      :disabled-date="disabledDate"
                      class="!w-full"
                    />
                  </el-form-item>

                  <!-- 出行人数 -->
                  <el-form-item label="出行人数" prop="people">
                    <el-input-number
                      v-model="form.people"
                      :min="1"
                      :max="10"
                      class="!w-full"
                    />
                  </el-form-item>

                  <!-- 预算范围 -->
                  <el-form-item label="预算范围" prop="budget">
                    <el-select v-model="form.budget" class="!w-full">
                      <el-option
                        label="超值型（500元/人）"
                        value="ultra_economy"
                      />
                      <el-option
                        label="经济型（1000元/人）"
                        value="economy"
                      />
                      <el-option
                        label="舒适型（1500元/人）"
                        value="medium"
                      />
                      <el-option 
                        label="品质型（2000元/人）"
                        value="quality"
                      />
                      <el-option 
                        label="豪华型（2500元/人）"
                        value="luxury"
                      />
                      <el-option 
                        label="尊享型（3000元以上/人）"
                        value="premium"
                      />
                    </el-select>
                  </el-form-item>
                </div>
              </div>

              <!-- 偏好设置 -->
              <div class="form-section pt-6 border-t dark:border-gray-700">
                <h2
                  class="text-xl font-medium text-gray-900 dark:text-white mb-6 flex items-center"
                >
                  <el-icon class="mr-2"><Star /></el-icon>
                  偏好设置
                </h2>

                <!-- 偏好景点 -->
                <el-form-item label="想去的景点" prop="spots">
                  <div v-if="loading" class="flex items-center justify-center py-4">
                    <el-skeleton :rows="3" animated />
                  </div>
                  <template v-else>
                    <el-select
                      v-model="form.spots"
                      multiple
                      filterable
                      class="!w-full"
                      placeholder="选择想去的景点（可多选）"
                      :loading="loading"
                    >
                      <el-option
                        v-for="spot in spots"
                        :key="spot.value"
                        :label="spot.label"
                        :value="spot.value"
                      >
                        <div class="flex items-center">
                          <el-image
                            :src="spot.image"
                            class="w-10 h-10 rounded object-cover mr-3"
                            :preview-src-list="[spot.image]"
                          >
                            <template #error>
                              <div class="image-slot flex items-center justify-center w-10 h-10 bg-gray-200">
                                <el-icon><Picture /></el-icon>
                              </div>
                            </template>
                          </el-image>
                          <div>
                            <div class="font-medium">{{ spot.label }}</div>
                            <div class="text-xs text-gray-500">
                              {{ spot.description }}
                            </div>
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                    
                    <!-- 所选景点预览 -->
                    <div v-if="form.spots.length > 0" class="selected-spots-preview mt-4">
                      <div class="text-sm text-gray-500 mb-2">已选择 {{ form.spots.length }} 个景点:</div>
                      <div class="flex flex-wrap gap-2">
                        <el-tag
                          v-for="spotId in form.spots"
                          :key="spotId"
                          closable
                          @close="removeSelectedSpot(spotId)"
                        >
                          {{ getSpotNameById(spotId) }}
                        </el-tag>
                      </div>
                    </div>
                    
                    <!-- 智能推荐 -->
                    <div v-if="form.spots.length > 0 && getSpotsRecommendation().length > 0" class="mt-4">
                      <div class="flex items-center text-sm text-gray-500 mb-2">
                        <el-icon class="mr-1"><Cpu /></el-icon>
                        <span>根据您的选择，可能还会喜欢:</span>
                      </div>
                      <div class="flex flex-wrap gap-2">
                        <el-button
                          v-for="spot in getSpotsRecommendation()"
                          :key="spot.value"
                          size="small"
                          @click="addRecommendedSpot(spot.value)"
                        >
                          {{ spot.label }}
                        </el-button>
                      </div>
                    </div>
                  </template>
                </el-form-item>

                <!-- 特殊需求 -->
                <el-form-item label="特殊需求" prop="requirements">
                  <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div
                      v-for="req in requirementOptions"
                      :key="req.value"
                      class="requirement-card"
                      :class="{
                        'is-active': form.requirements.includes(req.value),
                      }"
                      @click="toggleRequirement(req.value)"
                    >
                      <el-icon class="text-2xl mb-2">
                        <component :is="req.icon" />
                      </el-icon>
                      <span>{{ req.label }}</span>
                    </div>
                  </div>
                </el-form-item>

                <!-- 其他备注 -->
                <el-form-item label="其他备注" prop="remarks">
                  <el-input
                    v-model="form.remarks"
                    type="textarea"
                    :rows="3"
                    placeholder="有什么特别的要求或偏好都可以告诉 AI"
                    resize="none"
                  />
                </el-form-item>
              </div>

              <!-- 生成按钮 -->
              <div class="flex justify-center pt-6">
                <el-button
                  type="primary"
                  size="large"
                  :loading="generating"
                  :disabled="form.spots.length === 0"
                  class="w-full md:w-auto !px-8"
                  @click="generateGuide"
                >
                  <el-icon class="mr-2"><Magic /></el-icon>
                  {{ generating ? "正在生成攻略..." : "生成专属攻略" }}
                </el-button>
              </div>
              
              <!-- 生成中的提示 -->
              <div v-if="generating" class="text-center text-sm text-gray-500 mt-2 animate-pulse">
                AI 正在为您生成攻略，大约需要 10-20 秒...
              </div>
            </el-form>
          </div>
        </div>

        <!-- 右侧预览区域 -->
        <div class="lg:w-96 flex-shrink-0 space-y-6">
          <!-- AI 助手介绍 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
            <div class="flex items-center space-x-4 mb-4">
              <div
                class="w-16 h-16 rounded-full bg-primary-100 dark:bg-primary-900 flex items-center justify-center"
              >
                <el-icon
                  class="text-3xl text-primary-600 dark:text-primary-400"
                >
                  <Cpu />
                </el-icon>
              </div>
              <div>
                <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                  DeepSeek AI 助手
                </h3>
                <p class="text-sm text-gray-500 dark:text-gray-400">
                  您的专属旅行规划专家
                </p>
              </div>
            </div>
            <div class="space-y-4 text-sm text-gray-600 dark:text-gray-400">
              <p>🎯 基于您的偏好，智能规划最优行程</p>
              <p>⏰ 合理安排游玩时间，避免行程过于紧凑</p>
              <p>💰 根据预算推荐合适的景点和美食</p>
              <p>🎨 提供专业的游玩建议和注意事项</p>
            </div>
          </div>

          <!-- 使用说明 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Document /></el-icon>
              使用说明
            </h3>
            <div class="space-y-1">
              <div class="guide-step">
                <div class="step-number">1</div>
                <div class="step-content">
                  <h4 class="text-sm font-medium text-gray-900 dark:text-white">
                    填写基本信息
                  </h4>
                  <p class="text-xs text-gray-500">
                    设置游玩天数、出行时间、人数和预算范围
                  </p>
                </div>
              </div>
              <div class="guide-step">
                <div class="step-number">2</div>
                <div class="step-content">
                  <h4 class="text-sm font-medium text-gray-900 dark:text-white">
                    选择偏好景点
                  </h4>
                  <p class="text-xs text-gray-500">
                    选择想要游览的景点，AI 会据此规划路线
                  </p>
                </div>
              </div>
              <div class="guide-step">
                <div class="step-number">3</div>
                <div class="step-content">
                  <h4 class="text-sm font-medium text-gray-900 dark:text-white">
                    设置特殊需求
                  </h4>
                  <p class="text-xs text-gray-500">
                    勾选特殊需求，让行程更符合您的期望
                  </p>
                </div>
              </div>
              <div class="guide-step">
                <div class="step-number">4</div>
                <div class="step-content">
                  <h4 class="text-sm font-medium text-gray-900 dark:text-white">
                    生成专属攻略
                  </h4>
                  <p class="text-xs text-gray-500">
                    AI 会为您生成一份详细的行程规划
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 生成结果展示 -->
      <div v-if="generatedGuide" class="mt-8 generated-guide">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-8">
          <!-- 结果头部 -->
          <div class="flex justify-between items-center mb-8">
            <div>
              <h2 class="text-2xl font-bold text-gray-900 dark:text-white">
                为您生成的{{ form.days }}日游攻略
              </h2>
              <p class="text-gray-600 dark:text-gray-400 mt-2">
                根据您的偏好，AI 为您规划了以下行程
              </p>
            </div>
            <div class="flex space-x-4">
              <el-button type="primary" @click="saveGuide">
                <el-icon class="mr-1"><Download /></el-icon>
                保存攻略
              </el-button>
              <el-button @click="shareGuide">
                <el-icon class="mr-1"><Share /></el-icon>
                分享攻略
              </el-button>
            </div>
          </div>

          <!-- AI评价 -->
          <div class="mb-8 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-100 dark:border-blue-800">
            <div class="flex items-start">
              <div class="w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-800 flex items-center justify-center mr-4 flex-shrink-0">
                <el-icon class="text-xl text-blue-600 dark:text-blue-400"><Cpu /></el-icon>
              </div>
              <div class="flex-1">
                <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">AI 攻略评价</h3>
                <p class="text-gray-700 dark:text-gray-300 mb-3">
                  根据您选择的{{ form.spots.length }}个景点和{{ form.days }}天行程安排，这份攻略{{ getAIEvaluation() }}
                </p>
                <div class="text-gray-600 dark:text-gray-400 mb-3 text-sm">
                  <p class="mb-2">
                    <strong>景点分布：</strong> {{ getSpotDistributionEvaluation() }}
                  </p>
                  <p class="mb-2">
                    <strong>行程节奏：</strong> {{ getTravelPaceEvaluation() }}
                  </p>
                  <p class="mb-2">
                    <strong>预算评估：</strong> {{ getBudgetEvaluation() }}
                  </p>
                  <p class="mb-2">
                    <strong>适合人群：</strong> {{ getSuitableGroupEvaluation() }}
                  </p>
                </div>
                <div class="mt-3 grid grid-cols-3 gap-2">
                  <div class="flex items-center">
                    <div class="w-2 h-2 rounded-full" :class="getSpotDistributionColor()" mr-2></div>
                    <span class="text-sm text-gray-600 dark:text-gray-400">景点分布</span>
                  </div>
                  <div class="flex items-center">
                    <div class="w-2 h-2 rounded-full" :class="getPaceColor()" mr-2></div>
                    <span class="text-sm text-gray-600 dark:text-gray-400">行程节奏</span>
                  </div>
                  <div class="flex items-center">
                    <div class="w-2 h-2 rounded-full bg-{{ getAIWarnColor() }}-500 mr-2"></div>
                    <span class="text-sm text-gray-600 dark:text-gray-400">{{ getAIWarnText() }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 行程概览 -->
          <div class="mb-8">
            <h3
              class="text-xl font-medium text-gray-900 dark:text-white mb-6 flex items-center"
            >
              <el-icon class="mr-2"><Calendar /></el-icon>
              行程概览
            </h3>
            <el-timeline>
              <el-timeline-item
                v-for="(day, index) in generatedGuide.itinerary"
                :key="index"
                :type="getTimelineItemType(index)"
                :timestamp="'第' + (index + 1) + '天'"
                placement="top"
              >
                <div class="timeline-card">
                  <h4 class="text-lg font-medium mb-3">{{ day.title }}</h4>
                  <div class="space-y-2">
                    <div
                      v-for="(spot, spotIndex) in day.spots"
                      :key="spotIndex"
                      class="flex items-center text-sm"
                    >
                      <span class="time-tag">{{ spot.time }}</span>
                      <span class="spot-name">{{ spot.name }}</span>
                    </div>
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>

          <!-- 每日详细行程 -->
          <div class="space-y-8">
            <div
              v-for="(day, index) in generatedGuide.itinerary"
              :key="index"
              class="day-detail-card"
            >
              <h3
                class="text-xl font-medium text-gray-900 dark:text-white mb-6 flex items-center"
              >
                <span class="day-number">{{ index + 1 }}</span>
                {{ day.title }}
              </h3>
              <div class="space-y-6">
                <div
                  v-for="(spot, spotIndex) in day.spots"
                  :key="spotIndex"
                  class="spot-detail-card"
                >
                  <div class="flex items-center justify-between mb-4">
                    <h4 class="text-lg font-medium flex items-center">
                      <el-icon class="mr-2"><Location /></el-icon>
                      {{ spot.name }}
                    </h4>
                    <span class="text-sm text-gray-500">{{ spot.time }}</span>
                  </div>
                  <p class="text-gray-600 dark:text-gray-400 mb-4">
                    {{ spot.description }}
                  </p>
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                    <div class="tip-card" v-if="spot.tips">
                      <el-icon><InfoFilled /></el-icon>
                      <span>{{ spot.tips }}</span>
                    </div>
                    <div class="tip-card" v-if="spot.transportation">
                      <el-icon><Van /></el-icon>
                      <span>{{ spot.transportation }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 费用预算 -->
          <div class="mt-8 pt-8 border-t dark:border-gray-700">
            <h3
              class="text-xl font-medium text-gray-900 dark:text-white mb-6 flex items-center"
            >
              <el-icon class="mr-2"><Money /></el-icon>
              费用预算
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div
                v-for="(category, index) in generatedGuide.budget"
                :key="index"
                class="budget-card"
              >
                <h4 class="text-lg font-medium mb-2">{{ category.name }}</h4>
                <div
                  class="text-2xl font-bold text-primary-600 dark:text-primary-400"
                >
                  ¥{{ category.amount }}
                </div>
                <div class="text-sm text-gray-500 mt-2" v-html="category.description"></div>
              </div>
            </div>
            
            <!-- 总预算 -->
            <div class="mt-6 p-4 bg-gray-50 dark:bg-gray-700/30 rounded-lg">
              <div class="flex justify-between items-center">
                <div class="text-lg font-medium">总预算 ({{ form.people }}人)</div>
                <div class="text-2xl font-bold text-primary-600 dark:text-primary-400">
                  ¥{{ getTotalBudget() }}
                </div>
              </div>
              <div class="text-sm text-gray-500 mt-2">
                <div><span class="font-medium">预算类型:</span> {{ getBudgetTypeText() }}</div>
                <div class="mt-1"><span class="font-medium">预算标准:</span> ¥{{ getBudgetPerPerson() }}元/人</div>
                <div class="mt-1"><span class="font-medium">实际人均:</span> ¥{{ Math.round(getTotalBudget() / form.people) }}元/人</div>
                <div class="mt-1"><span class="font-medium">总计天数:</span> {{ form.days }}天</div>
              </div>
            </div>
          </div>

          <!-- 注意事项 -->
          <div class="mt-8 pt-8 border-t dark:border-gray-700">
            <h3
              class="text-xl font-medium text-gray-900 dark:text-white mb-6 flex items-center"
            >
              <el-icon class="mr-2"><Warning /></el-icon>
              注意事项
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div
                v-for="(note, index) in generatedGuide.notes"
                :key="index"
                class="note-card"
              >
                <h4 class="text-lg font-medium mb-2">{{ note.title }}</h4>
                <p class="text-gray-600 dark:text-gray-400">
                  {{ note.content }}
                </p>
              </div>
            </div>
          </div>
          
          <!-- 反馈区域 -->
          <div class="mt-8 pt-8 border-t dark:border-gray-700">
            <h3 class="text-xl font-medium text-gray-900 dark:text-white mb-4 flex items-center">
              <el-icon class="mr-2"><Comment /></el-icon>
              攻略反馈
            </h3>
            <div class="p-4 bg-gray-50 dark:bg-gray-700/30 rounded-lg">
              <p class="text-gray-600 dark:text-gray-400 mb-4">这份攻略对您有帮助吗？</p>
              <div class="flex space-x-4">
                <el-button :type="feedback === 'good' ? 'success' : 'default'" @click="submitFeedback('good')">
                  <el-icon class="mr-1"><ThumbUp /></el-icon>
                  很有帮助
                </el-button>
                <el-button :type="feedback === 'neutral' ? 'warning' : 'default'" @click="submitFeedback('neutral')">
                  <el-icon class="mr-1"><TurnOff /></el-icon>
                  一般
                </el-button>
                <el-button :type="feedback === 'bad' ? 'danger' : 'default'" @click="submitFeedback('bad')">
                  <el-icon class="mr-1"><ThumbDown /></el-icon>
                  需要改进
                </el-button>
              </div>
              <div v-if="feedback === 'bad'" class="mt-4">
                <el-input 
                  v-model="feedbackComment" 
                  type="textarea" 
                  :rows="2" 
                  placeholder="您的宝贵意见将帮助我们改进AI攻略服务"
                  resize="none"
                />
                <div class="mt-2 flex justify-end">
                  <el-button type="primary" size="small" @click="submitDetailedFeedback">
                    提交反馈
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import {
  Back,
  Calendar,
  Cpu,
  Download,
  Document,
  InfoFilled,
  Location,
  Magic,
  Money,
  Share,
  Star,
  Van,
  Warning,
  Picture,
  Comment,
  ThumbUp,
  ThumbDown,
  TurnOff,
  Check,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import service from "@/api/axios"; // 导入axios实例

const router = useRouter();
const formRef = ref(null);
const generating = ref(false);
const loading = ref(false); // 添加加载状态

// API状态
const apiStatus = reactive({
  checked: false,
  available: false,
  message: ''
});

// 检查DeepSeek API可用性
const checkApiAvailability = async () => {
  try {
    const apiKey = 'sk-00bd991d61df441f94ca24a0ed2c4abd';
    const response = await fetch('https://api.deepseek.com/v1/models', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${apiKey}`
      }
    });
    
    if (response.ok) {
      apiStatus.available = true;
      apiStatus.message = 'API连接正常';
    } else {
      // 尝试使用代理
      try {
        const corsProxyUrl = 'https://cors-anywhere.herokuapp.com/';
        const proxyResponse = await fetch(corsProxyUrl + 'https://api.deepseek.com/v1/models', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${apiKey}`,
            'X-Requested-With': 'XMLHttpRequest'
          }
        });
        
        if (proxyResponse.ok) {
          apiStatus.available = true;
          apiStatus.message = 'API通过代理连接正常';
        } else {
          throw new Error('代理连接也失败');
        }
      } catch (proxyError) {
        apiStatus.available = false;
        apiStatus.message = '无法连接到API服务';
      }
    }
  } catch (error) {
    console.error("API健康检查失败:", error);
    apiStatus.available = false;
    apiStatus.message = '无法连接到API服务';
  } finally {
    apiStatus.checked = true;
  }
};

// 表单数据
const form = reactive({
  days: 1,
  date: "",
  people: 1,
  budget: "",
  spots: [],
  requirements: [],
  remarks: "",
});

// 表单规则
const rules = {
  days: [{ required: true, message: "请选择游玩天数", trigger: "change" }],
  date: [{ required: true, message: "请选择出行时间", trigger: "change" }],
  people: [{ required: true, message: "请选择出行人数", trigger: "change" }],
  budget: [{ required: true, message: "请选择预算范围", trigger: "change" }],
  spots: [{ required: true, message: "请至少选择一个景点", trigger: "change" }],
};

// 景点数据
const spots = ref([
  {
    value: 1,
    label: "贵港博物馆",
    image: "/images/spots/museum.jpg",
    description: "了解贵港历史文化的最佳去处",
  },
  {
    value: 2,
    label: "江滨公园",
    image: "/images/spots/riverside.jpg",
    description: "城市地标，江景优美",
  },
  {
    value: 3,
    label: "贵港美食街",
    image: "/images/spots/food.jpg",
    description: "汇集本地特色美食",
  },
  {
    value: 4,
    label: "观音山公园",
    image: "/images/spots/mountain.jpg",
    description: "登高望远，景色秀丽",
  },
  {
    value: 5,
    label: "石龙文化园",
    image: "/images/spots/culture.jpg",
    description: "感受本地特色文化",
  },
]);

// 从API获取景点数据
const fetchSpots = async () => {
  loading.value = true;
  try {
    // 构建筛选参数
    const params = {
      pageSize: 1000 // 设置一个足够大的数，确保获取所有数据
    };

    // 调用API获取景点列表
    const res = await service.get('/public/spot/list', { params });
    console.log("景点列表API响应:", res);
    
    let allSpots = [];
    
    // 检查所有可能的数据结构模式
    if (res.data && res.data.content && Array.isArray(res.data.content)) {
      allSpots = [...res.data.content];
    } 
    else if (res.data && res.data.code === 200 && res.data.data && res.data.data.content && Array.isArray(res.data.data.content)) {
      allSpots = [...res.data.data.content];
    }
    else if (res.data && res.data.data && res.data.data.records && Array.isArray(res.data.data.records)) {
      allSpots = [...res.data.data.records];
    }
    else if (res.data && res.data.data && Array.isArray(res.data.data)) {
      allSpots = [...res.data.data];
    }
    else if (res.data && Array.isArray(res.data)) {
      allSpots = [...res.data];
    }
    else {
      console.error("未能识别的API响应格式:", res.data);
      
      // 尝试一种最后的解析方法 - 遍历res.data寻找数组
      if (res.data) {
        for (const key in res.data) {
          if (Array.isArray(res.data[key]) && res.data[key].length > 0) {
            console.log(`找到数组字段: ${key}, 长度: ${res.data[key].length}`);
            if (res.data[key][0] && (res.data[key][0].name || res.data[key][0].title) && res.data[key][0].id) {
              console.log("数组内容有效，使用此数据");
              allSpots = [...res.data[key]];
              break;
            }
          }
        }
      }
    }
    
    // 格式化数据为组件所需格式
    if (allSpots.length > 0) {
      console.log("成功获取到API数据:", allSpots.length, "条");
      
      // 将API数据转换为spots所需的格式
      spots.value = allSpots.map(spot => ({
        value: spot.id,
        label: spot.name || spot.title || '未命名景点',
        image: spot.coverImage || spot.cover || spot.image || '/images/spots/default.jpg',
        description: spot.description || spot.desc || '暂无描述'
      }));
      
      console.log("转换后的景点数据:", spots.value.slice(0, 2));
    } else {
      console.warn("API返回的数据解析为空，使用默认数据");
      // 默认数据在初始化时已设置
    }
  } catch (error) {
    console.error("获取景点列表失败:", error);
    ElMessage.warning("获取景点数据失败，使用默认数据");
    // 保留默认数据
  } finally {
    loading.value = false;
  }
};

// 特殊需求选项
const requirementOptions = [
  { label: "摄影打卡", value: "photo", icon: "Camera" },
  { label: "美食探索", value: "food", icon: "Food" },
  { label: "文化体验", value: "culture", icon: "Collection" },
  { label: "亲子活动", value: "family", icon: "User" },
];

// 生成的攻略数据
const generatedGuide = ref(null);

// 禁用日期（今天之前的日期）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
};

// 切换特殊需求
const toggleRequirement = (value) => {
  const index = form.requirements.indexOf(value);
  if (index === -1) {
    form.requirements.push(value);
  } else {
    form.requirements.splice(index, 1);
  }
};

// 获取时间线项目类型
const getTimelineItemType = (index) => {
  const types = ["primary", "success", "warning", "danger"];
  return types[index % types.length];
};

// 生成攻略
const generateGuide = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    generating.value = true;

    // 获取表单数据
    const formData = {
      days: form.days,
      date: form.date instanceof Date ? form.date.toISOString().split('T')[0] : form.date,
      people: form.people,
      budget: form.budget,
      spots: form.spots,
      requirements: form.requirements,
      remarks: form.remarks
    };

    console.log("生成攻略的数据:", formData);

    // 获取所选景点的详细信息
    const selectedSpots = spots.value.filter(spot => form.spots.includes(spot.value));
    
    // 调用DeepSeek API生成攻略
    const travelGuide = await generateAITravelGuide(formData, selectedSpots);
    
    // 保存生成的攻略
    generatedGuide.value = travelGuide;
    
    // 滚动到攻略结果区域
    setTimeout(() => {
      const resultElement = document.querySelector('.generated-guide');
      if (resultElement) {
        resultElement.scrollIntoView({ behavior: 'smooth' });
      }
    }, 200);

    ElMessage.success("攻略生成成功！");
  } catch (error) {
    console.error("生成攻略失败:", error);
    ElMessage.error("攻略生成失败：" + (error.message || "请完善必填信息"));
  } finally {
    generating.value = false;
  }
};

// 调用DeepSeek API生成攻略
const generateAITravelGuide = async (formData, selectedSpots) => {
  try {
    const { days, date, people, budget, requirements, remarks } = formData;
    
    // 预算类型文本
    const budgetText = {
      'ultra_economy': '超值型（500元）',
      'economy': '经济型（1000元）',
      'medium': '舒适型（1500元）',
      'quality': '品质型（2000元）',
      'luxury': '豪华型（2500元）',
      'premium': '尊享型（3000元以上）'
    }[budget] || '中等预算';
    
    // 特殊需求文本
    const requirementsText = requirements.map(req => {
      const option = requirementOptions.find(o => o.value === req);
      return option ? option.label : req;
    }).join('、');
    
    // 景点列表文本
    const spotsText = selectedSpots.map(spot => spot.label).join('、');
    
    // 构建提示词
    const prompt = `请你作为一名旅游攻略专家，为用户生成一份贵港旅游攻略。以下是用户的需求：

游玩天数: ${days}天
出行时间: ${date}
出行人数: ${people}人
预算范围: ${budgetText}
想去的景点: ${spotsText}
特殊需求: ${requirementsText || '无特殊需求'}
其他备注: ${remarks || '无'}

请根据以上信息，生成一份详细的贵港旅游攻略，包括：
1. 每日行程安排（包括景点、用餐、交通等）
2. "第X天：XXX、XXX" 格式的标题
3. 每个景点的游览时间（如 "09:00-11:00"）
4. 景点描述和小贴士
5. 交通建议
6. 费用预算（分为住宿、餐饮、交通、门票、其他几个类别）
7. 注意事项（4-5条即可）

请以JSON格式返回，格式如下：
\`\`\`json
{
  "itinerary": [
    {
      "title": "第1天：XX景点、XX景点",
      "spots": [
        {
          "name": "景点名称",
          "time": "时间段",
          "description": "景点描述",
          "tips": "参观建议",
          "transportation": "交通信息"
        }
      ]
    }
  ],
  "budget": [
    {
      "name": "类别名称",
      "amount": 金额,
      "description": "费用说明"
    }
  ],
  "notes": [
    {
      "title": "注意事项标题",
      "content": "注意事项内容"
    }
  ]
}
\`\`\`

只返回JSON数据，不要有任何其他文字。`;

    console.log("发送到DeepSeek的提示词:", prompt);
    
    // API请求参数
    const apiKey = 'sk-00bd991d61df441f94ca24a0ed2c4abd';
    const apiUrl = 'https://api.deepseek.com/v1/chat/completions';
    const apiData = {
      model: 'deepseek-chat',
      messages: [
        {
          role: 'system',
          content: '你是一名专业的旅游攻略生成助手，擅长根据用户需求制定详细的旅游行程计划。请直接以JSON格式输出结果，不要添加任何额外解释。交通、美食建议板块的推荐尽量数据真实。'
        },
        {
          role: 'user',
          content: prompt
        }
      ],
      temperature: 0.7,
      max_tokens: 4000
    };
    
    let response;
    
    try {
      // 直接调用API
      response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify(apiData)
      });
    } catch (fetchError) {
      console.error("API请求错误 - 可能是CORS问题:", fetchError);
      
      // 尝试使用CORS代理
      ElMessage.warning("正在尝试备用API调用方式，请稍候...");
      
      try {
        // 使用CORS代理
        const corsProxyUrl = 'https://cors-anywhere.herokuapp.com/';
        response = await fetch(corsProxyUrl + apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`,
            'X-Requested-With': 'XMLHttpRequest' // 告诉CORS代理这是一个合法请求
          },
          body: JSON.stringify(apiData)
        });
      } catch (proxyError) {
        console.error("CORS代理请求也失败:", proxyError);
        ElMessage.error("API访问失败，将使用基础模板生成攻略");
        return generateFallbackTravelGuide(formData, selectedSpots);
      }
    }
    
    if (!response.ok) {
      let errorText = '';
      try {
        const errorData = await response.json();
        errorText = errorData.error?.message || `HTTP错误 ${response.status}`;
      } catch (e) {
        errorText = `HTTP错误 ${response.status}`;
      }
      
      console.error("API响应错误:", errorText);
      ElMessage.error(`AI服务错误: ${errorText}`);
      return generateFallbackTravelGuide(formData, selectedSpots);
    }
    
    const data = await response.json();
    console.log("DeepSeek API返回数据:", data);
    
    // 提取API返回的内容
    const content = data.choices[0]?.message?.content;
    if (!content) {
      throw new Error('API返回数据格式错误');
    }
    
    // 提取JSON部分
    let jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/) || 
                   content.match(/```\s*([\s\S]*?)\s*```/) || 
                   [null, content];
    
    let jsonText = jsonMatch[1] || content;
    
    // 尝试解析JSON
    try {
      // 清理JSON文本，确保是有效的JSON
      jsonText = jsonText.trim();
      // 确保开头是 {
      if (!jsonText.startsWith('{')) {
        const startIndex = jsonText.indexOf('{');
        if (startIndex >= 0) {
          jsonText = jsonText.substring(startIndex);
        }
      }
      // 确保结尾是 }
      if (!jsonText.endsWith('}')) {
        const endIndex = jsonText.lastIndexOf('}');
        if (endIndex >= 0) {
          jsonText = jsonText.substring(0, endIndex + 1);
        }
      }
      
      const travelGuide = JSON.parse(jsonText);
      
      // 验证返回的数据格式
      if (!travelGuide.itinerary || !travelGuide.budget || !travelGuide.notes) {
        console.warn("返回的数据结构不完整:", travelGuide);
        throw new Error('返回的数据结构不完整');
      }
      
      ElMessage.success("AI攻略生成成功");
      return travelGuide;
    } catch (parseError) {
      console.error("JSON解析错误:", parseError, "原文本:", jsonText);
      
      // 尝试修复常见的JSON错误
      try {
        let fixedJson = jsonText
          .replace(/[\u201C\u201D]/g, '"') // 替换中文引号
          .replace(/(\w+):/g, '"$1":') // 给没引号的键名加引号
          .replace(/,\s*}/g, '}') // 修复对象末尾多余的逗号
          .replace(/,\s*]/g, ']'); // 修复数组末尾多余的逗号
        
        // 最后一次尝试，用正则捕获所有 key-value 对
        if (!fixedJson.startsWith('{')) {
          fixedJson = '{' + fixedJson;
        }
        if (!fixedJson.endsWith('}')) {
          fixedJson = fixedJson + '}';
        }
        
        const travelGuide = JSON.parse(fixedJson);
        if (!travelGuide.itinerary || !travelGuide.budget || !travelGuide.notes) {
          throw new Error('修复后的数据结构仍不完整');
        }
        
        ElMessage.warning("AI返回的数据有些问题，已尝试修复");
        return travelGuide;
      } catch (e) {
        // 如果修复失败，则构建一个简单的回退模板
        console.error("JSON修复失败，使用基础模板:", e);
        ElMessage.error("无法解析AI返回的数据，使用基础模板");
        return generateFallbackTravelGuide(formData, selectedSpots);
      }
    }
  } catch (error) {
    console.error("调用DeepSeek API失败:", error);
    ElMessage.error("AI服务调用失败: " + error.message);
    // 出错时返回一个基本模板
    return generateFallbackTravelGuide(formData, selectedSpots);
  }
};

// 回退方案：生成基本的旅游攻略模板
const generateFallbackTravelGuide = (formData, selectedSpots) => {
  const { days, people, budget, requirements } = formData;
  
  // 生成行程安排
  const itinerary = generateItinerary(days, selectedSpots, requirements);
  
  // 生成预算
  const budgetDetails = generateBudget(days, people, budget, selectedSpots);
  
  // 生成注意事项
  const notes = generateAllNotes(formData, selectedSpots);
  
  ElMessage.warning('AI攻略生成出现问题，已使用本地模板');
  
  // 返回完整攻略
  return {
    itinerary,
    budget: budgetDetails,
    notes
  };
};

// 根据景点和天数生成行程
const generateItinerary = (days, selectedSpots, requirements) => {
  const itinerary = [];
  
  // 复制景点列表，确保可以合理分配
  let spotsPool = [...selectedSpots];
  
  // 如果景点不够，添加一些附近景点
  if (spotsPool.length < days * 2) {
    // 添加一些附近的景点
    const nearbySpots = [
      { value: 100, label: "贵港特色美食一条街", description: "品尝当地特色美食的好去处" },
      { value: 101, label: "贵港夜市", description: "感受当地夜生活的繁华" },
      { value: 102, label: "贵港文化广场", description: "当地市民休闲娱乐的中心" },
      { value: 103, label: "贵港艺术中心", description: "欣赏当地艺术表演的场所" },
      { value: 104, label: "贵港湿地公园", description: "城市中的生态绿洲" }
    ];
    
    spotsPool = [...spotsPool, ...nearbySpots];
  }
  
  // 均匀分配景点到每天
  for (let i = 0; i < days; i++) {
    // 每天游览2-4个景点，根据天数动态调整
    const spotsPerDay = Math.max(2, Math.min(4, Math.floor(spotsPool.length / (days - i || 1))));
    
    // 从景点池中取出当天要游览的景点
    const daySpots = spotsPool.splice(0, spotsPerDay);
    
    // 生成当天的游览时间安排
    const daySchedule = generateDaySchedule(daySpots, requirements, i);
    
    // 添加当天行程
    itinerary.push({
      title: `第${i+1}天：${daySpots.map(s => s.label).join('、')}`,
      spots: daySchedule
    });
  }
  
  return itinerary;
};

// 生成单日行程安排
const generateDaySchedule = (daySpots, requirements, dayIndex) => {
  // 生成当天的游览时间安排
  const daySchedule = daySpots.map((spot, idx) => {
    // 根据位置分配不同的时间段
    let timeSlot;
    if (idx === 0) {
      timeSlot = "09:00 - 11:00";
    } else if (idx === daySpots.length - 1) {
      timeSlot = "16:00 - 18:00";
    } else if (idx === 1) {
      timeSlot = "13:00 - 15:00";
    } else {
      timeSlot = "15:00 - 16:00";
    }
    
    // 生成景点参观信息
    return {
      name: spot.label,
      time: timeSlot,
      description: spot.description || "暂无描述",
      tips: generateSimpleSpotTips(spot, requirements),
      transportation: idx === 0 ? 
        (dayIndex === 0 ? "酒店出发，建议打车前往" : "从酒店出发，建议打车前往") : 
        "从上一景点步行或打车约15分钟"
    };
  });
  
  // 添加用餐时间
  if (daySchedule.length >= 2) {
    // 在上午和下午景点之间插入午餐
    daySchedule.splice(1, 0, {
      name: "午餐时间",
      time: "11:30 - 13:00",
      description: "在附近餐厅享用当地特色美食",
      tips: requirements.includes("food") ? "推荐尝试贵港特色小吃，如粉利、老友粉等" : "可选择当地人气餐厅",
      transportation: "从上一景点步行前往附近餐厅"
    });
  }
  
  // 添加晚餐
  daySchedule.push({
    name: "晚餐时间",
    time: "18:30 - 20:00",
    description: "享用晚餐，休息放松",
    tips: requirements.includes("food") ? "推荐品尝本地特色河鲜" : "可选择酒店附近餐厅",
    transportation: "从上一景点返回酒店附近"
  });
  
  return daySchedule;
};

// 生成简单景点小贴士
const generateSimpleSpotTips = (spot, requirements) => {
  // 根据不同类型的景点和用户需求生成不同的贴士
  const spotName = spot.label.toLowerCase();
  
  if (spotName.includes("博物馆") || spotName.includes("纪念馆")) {
    return "博物馆一般每周一闭馆，参观时请保持安静，注意展品保护";
  }
  
  if (spotName.includes("公园") || spotName.includes("山") || spotName.includes("湖")) {
    return "自然景区游览建议穿舒适鞋子，带防晒用品，保护环境不乱扔垃圾";
  }
  
  if (spotName.includes("古镇") || spotName.includes("街") || spotName.includes("文化")) {
    return "历史文化街区适合慢慢品味，可尝试当地特色小吃，购买手工艺品";
  }
  
  if (spotName.includes("美食") || spotName.includes("夜市")) {
    return "美食街区品尝时注意食品卫生，可多尝试不同店铺，比较口味";
  }
  
  // 默认提示
  return "建议提前查询开放时间，避开人流高峰";
};

// 生成预算详情
const generateBudget = (days, people, budgetType, selectedSpots) => {
  // 根据预算类型设置总预算标准 (每人)
  let totalBudgetPerPerson = 0;
  
  switch (budgetType) {
    case 'ultra_economy':
      totalBudgetPerPerson = 500; // 超值型（500元/人）
      break;
    case 'economy':
      totalBudgetPerPerson = 1000; // 经济型（1000元/人）
      break;
    case 'medium':
      totalBudgetPerPerson = 1500; // 舒适型（1500元/人）
      break;
    case 'quality':
      totalBudgetPerPerson = 2000; // 品质型（2000元/人）
      break;
    case 'luxury':
      totalBudgetPerPerson = 2500; // 豪华型（2500元/人）
      break;
    case 'premium':
      totalBudgetPerPerson = 3000; // 尊享型（3000元以上/人）
      break;
    default:
      totalBudgetPerPerson = 1200; // 默认
  }
  
  // 总预算
  const totalBudget = totalBudgetPerPerson * people;
  
  // 根据预算类型设置住宿标准 (每晚每人)
  let accommodationPerPersonPerNight = 0;
  
  switch (budgetType) {
    case 'ultra_economy':
      accommodationPerPersonPerNight = 100; // 超值型
      break;
    case 'economy':
      accommodationPerPersonPerNight = 150; // 经济型
      break;
    case 'medium':
      accommodationPerPersonPerNight = 300; // 舒适型
      break;
    case 'quality':
      accommodationPerPersonPerNight = 400; // 品质型
      break;
    case 'luxury':
      accommodationPerPersonPerNight = 600; // 豪华型
      break;
    case 'premium':
      accommodationPerPersonPerNight = 800; // 尊享型
      break;
    default:
      accommodationPerPersonPerNight = 200; // 默认
  }
  
  // 计算住宿总费用 (天数-1晚)
  const accommodationDays = Math.max(1, days - 1); // 至少住一晚
  const accommodationTotal = Math.round(accommodationPerPersonPerNight * people * accommodationDays);
  
  // 生成房间分配方案
  let roomArrangement = "";
  let roomRate = 0;
  
  if (people === 1) {
    roomArrangement = "1间单人房";
    roomRate = accommodationPerPersonPerNight;
  } else if (people === 2) {
    roomArrangement = "1间双人房";
    roomRate = accommodationPerPersonPerNight * 2;
  } else if (people === 3) {
    roomArrangement = "1间三人房或1间双人房+1间单人房";
    roomRate = accommodationPerPersonPerNight * 3;
  } else if (people === 4) {
    roomArrangement = "2间双人房";
    roomRate = accommodationPerPersonPerNight * 2;
  } else {
    // 超过4人，按每2-3人一间房计算
    const doubleRooms = Math.floor(people / 2);
    const singleRooms = people % 2;
    roomArrangement = `${doubleRooms}间双人房` + (singleRooms > 0 ? `+${singleRooms}间单人房` : '');
    roomRate = accommodationPerPersonPerNight * 2;
  }
  
  // 住宿描述
  const accommodationDescription = `
    <div class="text-sm">
      <div class="mb-1">酒店等级：${getBudgetAccommodationLevel(budgetType)}</div>
      <div class="mb-1">房间安排：${roomArrangement}</div>
      <div class="mb-1">入住天数：${accommodationDays}晚</div>
      <div class="mb-1">标准房价：${roomRate}元/间/晚</div>
      <div class="mb-1">人均住宿：${accommodationPerPersonPerNight}元/人/晚</div>
      <div class="mb-1">总住宿费：${accommodationTotal}元</div>
    </div>
  `;
  
  // 计算餐饮费用 (每人每天三餐)
  let mealCostPerPersonPerDay = 0;
  let breakfastCost = 0;
  let lunchCost = 0;
  let dinnerCost = 0;
  let mealDescription = "";

  switch (budgetType) {
    case 'ultra_economy':
      breakfastCost = 10;
      lunchCost = 35;
      dinnerCost = 35;
      mealCostPerPersonPerDay = breakfastCost + lunchCost + dinnerCost; // 超值型
      break;
    case 'economy':
      breakfastCost = 20;
      lunchCost = 50;
      dinnerCost = 70;
      mealCostPerPersonPerDay = breakfastCost + lunchCost + dinnerCost; // 经济型
      break;
    case 'medium':
      breakfastCost = 30;
      lunchCost = 80;
      dinnerCost = 140;
      mealCostPerPersonPerDay = breakfastCost + lunchCost + dinnerCost; // 舒适型
      break;
    case 'quality':
      breakfastCost = 50;
      lunchCost = 120;
      dinnerCost = 230;
      mealCostPerPersonPerDay = breakfastCost + lunchCost + dinnerCost; // 品质型
      break;
    case 'luxury':
      breakfastCost = 80;
      lunchCost = 170;
      dinnerCost = 350;
      mealCostPerPersonPerDay = breakfastCost + lunchCost + dinnerCost; // 豪华型
      break;
    case 'premium':
      breakfastCost = 100;
      lunchCost = 250;
      dinnerCost = 550;
      mealCostPerPersonPerDay = breakfastCost + lunchCost + dinnerCost; // 尊享型
      break;
    default:
      breakfastCost = 25;
      lunchCost = 75;
      dinnerCost = 100;
      mealCostPerPersonPerDay = breakfastCost + lunchCost + dinnerCost; // 默认
  }

  // 计算餐饮总费用
  const mealTotal = Math.round(mealCostPerPersonPerDay * people * days);

  // 生成餐饮描述，详细列出每顿饭的费用
  mealDescription = `
    <div class="text-sm">
      <div class="mb-1">餐饮类型：${getBudgetFoodLevel(budgetType)}</div>
      <div class="mb-1">早餐标准：${breakfastCost}元/人/天</div>
      <div class="mb-1">午餐标准：${lunchCost}元/人/天</div>
      <div class="mb-1">晚餐标准：${dinnerCost}元/人/天</div>
      <div class="mb-1">天数：${days}天</div>
      <div class="mb-1">总人数：${people}人</div>
      <div class="mb-1">人均餐饮：${mealCostPerPersonPerDay}元/人/天</div>
      <div class="mb-1">总餐饮费：${mealTotal}元</div>
    </div>
  `;
  
  // 计算交通费用 (每人每天)
  let transportCostPerPersonPerDay = 0;
  let publicTransportCost = 0;
  let taxiCost = 0;
  let transportMode = "";

  switch (budgetType) {
    case 'ultra_economy':
      publicTransportCost = 30;
      taxiCost = 10;
      transportCostPerPersonPerDay = publicTransportCost + taxiCost; // 超值型
      transportMode = "公共交通为主，偶尔拼车";
      break;
    case 'economy':
      publicTransportCost = 40;
      taxiCost = 30;
      transportCostPerPersonPerDay = publicTransportCost + taxiCost; // 经济型
      transportMode = "公共交通为主，适当打车";
      break;
    case 'medium':
      publicTransportCost = 50;
      taxiCost = 100;
      transportCostPerPersonPerDay = publicTransportCost + taxiCost; // 舒适型
      transportMode = "公交与打车结合";
      break;
    case 'quality':
      publicTransportCost = 0;
      taxiCost = 250;
      transportCostPerPersonPerDay = publicTransportCost + taxiCost; // 品质型
      transportMode = "全程打车出行，可包车半天";
      break;
    case 'luxury':
      publicTransportCost = 0;
      taxiCost = 350;
      transportCostPerPersonPerDay = publicTransportCost + taxiCost; // 豪华型
      transportMode = "专车或全天包车服务";
      break;
    case 'premium':
      publicTransportCost = 0;
      taxiCost = 500;
      transportCostPerPersonPerDay = publicTransportCost + taxiCost; // 尊享型
      transportMode = "高端私人专车或SUV全天包车，含专业司机";
      break;
    default:
      publicTransportCost = 40;
      taxiCost = 60;
      transportCostPerPersonPerDay = publicTransportCost + taxiCost; // 默认
      transportMode = "公交打车结合";
  }

  // 计算交通总费用
  const transportTotal = Math.round(transportCostPerPersonPerDay * people * days);

  // 生成交通描述，详细列出交通方式和费用
  const transportDescription = `
    <div class="text-sm">
      <div class="mb-1">交通方式：${transportMode}</div>
      ${publicTransportCost > 0 ? `<div class="mb-1">公共交通：${publicTransportCost}元/人/天</div>` : ''}
      ${taxiCost > 0 ? `<div class="mb-1">出租车/专车：${taxiCost}元/人/天</div>` : ''}
      <div class="mb-1">天数：${days}天</div>
      <div class="mb-1">总人数：${people}人</div>
      <div class="mb-1">人均交通：${transportCostPerPersonPerDay}元/人/天</div>
      <div class="mb-1">总交通费：${transportTotal}元</div>
    </div>
  `;
  
  // 计算门票费用 (根据实际景点)
  const ticketTotal = calculateTicketsTotal(selectedSpots, people);
  
  // 计算其他费用 (购物、纪念品等)
  let otherCostPerPersonPerDay = 0;
  let shoppingDescription = "";
  let shoppingItems = [];

  switch (budgetType) {
    case 'ultra_economy':
      otherCostPerPersonPerDay = 30; // 超值型
      shoppingItems = [
        { name: "基本纪念品", cost: 20 },
        { name: "少量伴手礼", cost: 10 }
      ];
      break;
    case 'economy':
      otherCostPerPersonPerDay = 60; // 经济型
      shoppingItems = [
        { name: "纪念品", cost: 20 },
        { name: "小额伴手礼", cost: 20 },
        { name: "当地特产", cost: 20 }
      ];
      break;
    case 'medium':
      otherCostPerPersonPerDay = 120; // 舒适型
      shoppingItems = [
        { name: "特色纪念品", cost: 40 },
        { name: "伴手礼", cost: 40 },
        { name: "当地特产", cost: 40 }
      ];
      break;
    case 'quality':
      otherCostPerPersonPerDay = 200; // 品质型
      shoppingItems = [
        { name: "精品购物", cost: 80 },
        { name: "高质量伴手礼", cost: 70 },
        { name: "当地特产", cost: 50 }
      ];
      break;
    case 'luxury':
      otherCostPerPersonPerDay = 400; // 豪华型
      shoppingItems = [
        { name: "精品购物", cost: 150 },
        { name: "高端伴手礼", cost: 150 },
        { name: "文创产品", cost: 50 },
        { name: "当地特产", cost: 50 }
      ];
      break;
    case 'premium':
      otherCostPerPersonPerDay = 600; // 尊享型
      shoppingItems = [
        { name: "奢侈品购物", cost: 250 },
        { name: "高端定制伴手礼", cost: 200 },
        { name: "艺术品", cost: 100 },
        { name: "当地顶级特产", cost: 50 }
      ];
      break;
    default:
      otherCostPerPersonPerDay = 100; // 默认
      shoppingItems = [
        { name: "纪念品", cost: 30 },
        { name: "伴手礼", cost: 40 },
        { name: "当地特产", cost: 30 }
      ];
  }

  // 计算其他总费用
  const otherTotal = Math.round(otherCostPerPersonPerDay * people * days);

  // 构建其他费用描述
  let shoppingItemsText = shoppingItems.map(item => 
    `<div class="mb-1">${item.name}：${item.cost}元/人/天</div>`
  ).join('');

  const otherDescription = `
    <div class="text-sm">
      <div class="mb-1">购物类型：休闲购物、纪念品、伴手礼</div>
      ${shoppingItemsText}
      <div class="mb-1">天数：${days}天</div>
      <div class="mb-1">总人数：${people}人</div>
      <div class="mb-1">人均购物：${otherCostPerPersonPerDay}元/人/天</div>
      <div class="mb-1">总购物费：${otherTotal}元</div>
    </div>
  `;
  
  // 调整各项费用，确保总和接近预设的总预算
  let currentTotal = accommodationTotal + mealTotal + transportTotal + ticketTotal.total + otherTotal;
  
  // 如果计算的总和与预期总预算相差较大，调整各项金额
  if (Math.abs(currentTotal - totalBudget) > totalBudget * 0.1) {
    const adjustmentFactor = totalBudget / currentTotal;
    
    // 按比例调整每一项
    const adjustedAccommodationTotal = Math.round(accommodationTotal * adjustmentFactor);
    const adjustedMealTotal = Math.round(mealTotal * adjustmentFactor);
    const adjustedTransportTotal = Math.round(transportTotal * adjustmentFactor);
    const adjustedOtherTotal = Math.round(otherTotal * adjustmentFactor);
    // 门票不调整，因为这是固定费用
    
    return [
      {
        name: "住宿费用",
        amount: adjustedAccommodationTotal,
        description: accommodationDescription
      },
      {
        name: "餐饮费用",
        amount: adjustedMealTotal,
        description: mealDescription
      },
      {
        name: "交通费用",
        amount: adjustedTransportTotal,
        description: transportDescription
      },
      {
        name: "门票费用",
        amount: ticketTotal.total,
        description: ticketTotal.description
      },
      {
        name: "其他花费",
        amount: adjustedOtherTotal,
        description: otherDescription
      }
    ];
  }
  
  // 如果总和合理，使用原计算结果
  return [
    {
      name: "住宿费用",
      amount: accommodationTotal,
      description: accommodationDescription
    },
    {
      name: "餐饮费用",
      amount: mealTotal,
      description: mealDescription
    },
    {
      name: "交通费用",
      amount: transportTotal,
      description: transportDescription
    },
    {
      name: "门票费用",
      amount: ticketTotal.total,
      description: ticketTotal.description
    },
    {
      name: "其他花费",
      amount: otherTotal,
      description: otherDescription
    }
  ];
};

// 计算门票总费用
const calculateTicketsTotal = (selectedSpots, people) => {
  let totalTicketCost = 0;
  let freeSpots = 0;
  let paidSpots = 0;
  let ticketDetails = [];
  let spotsList = []; // 保存每个景点的详细信息
  
  // 获取每个景点的票价
  selectedSpots.forEach(spot => {
    // 提取票价信息 - 尝试从原始属性或description中提取
    let ticketPrice = 0;
    
    // 尝试从原始属性中获取价格信息
    if (spot.price !== undefined && !isNaN(Number(spot.price)) && spot.price > 0) {
      ticketPrice = Number(spot.price);
    } 
    // 尝试从描述中提取价格信息
    else if (spot.description) {
      const priceMatch = spot.description.match(/(\d+)元/);
      if (priceMatch) {
        ticketPrice = Number(priceMatch[1]);
      }
    }
    
    // 如果找不到价格信息，使用默认价格
    if (ticketPrice <= 0) {
      // 根据景点名称估算票价
      if (spot.label.includes('博物馆') || spot.label.includes('纪念馆')) {
        ticketPrice = spot.label.includes('国家') ? 60 : 30;
      } else if (spot.label.includes('公园')) {
        ticketPrice = spot.label.includes('国家') || spot.label.includes('风景区') ? 70 : 20;
      } else if (spot.label.includes('古镇') || spot.label.includes('古城')) {
        ticketPrice = 80;
      } else if (spot.label.includes('美食') || spot.label.includes('夜市') || spot.label.includes('广场')) {
        ticketPrice = 0; // 通常免费
      } else {
        ticketPrice = 40; // 默认票价
      }
    }
    
    // 累加票价
    const spotTotalPrice = ticketPrice * people;
    
    // 保存景点门票详情
    if (ticketPrice > 0) {
      totalTicketCost += spotTotalPrice;
      paidSpots++;
      ticketDetails.push(`${spot.label}(${ticketPrice}元/人)`);
      
      // 添加到详细景点列表
      spotsList.push({
        name: spot.label,
        price: ticketPrice,
        totalPrice: spotTotalPrice,
        isFree: false
      });
    } else {
      freeSpots++;
      spotsList.push({
        name: spot.label,
        price: 0,
        totalPrice: 0,
        isFree: true
      });
    }
  });
  
  // 生成描述
  let description = '';
  if (paidSpots > 0) {
    description = `<div class="text-sm">`;
    
    // 逐个列出每个景点门票
    spotsList.forEach(spot => {
      if (!spot.isFree) {
        description += `<div class="mb-1">${spot.name}：${spot.price}元/人 × ${people}人 = ${spot.totalPrice}元</div>`;
      }
    });
    
    // 显示免费景点
    if (freeSpots > 0) {
      description += `<div class="mt-2">另有${freeSpots}个免费景点</div>`;
    }
    
    description += `</div>`;
  } else if (freeSpots > 0) {
    description = `所选景点均为免费景点，无需门票费用`;
    // 添加一些其他费用避免为0
    totalTicketCost = people * freeSpots * 5; // 小额文创产品或指南购买
    description += `，预留少量费用用于景区地图或小纪念品`;
  } else {
    description = `暂无景点信息，门票费用待定`;
  }
  
  return {
    total: totalTicketCost,
    description: description,
    spotsList: spotsList  // 返回详细的景点列表，方便在UI中使用
  };
};

// 根据天气生成注意事项
const generateWeatherNote = (date) => {
  // 如果没有选择日期，返回通用提示
  if (!date) {
    return {
      title: "天气提醒",
      content: "贵港气候湿润，夏季炎热多雨，冬季温暖少雨。出行前建议查看天气预报，携带适当衣物、雨具和防晒用品。昼夜温差较大，请注意及时增减衣物，预防感冒。"
    };
  }
  
  // 将日期转换为时间对象
  const travelDate = new Date(date);
  const month = travelDate.getMonth() + 1; // 月份从0开始
  
  // 根据不同月份生成对应的天气提示
  if (month >= 6 && month <= 9) {
    // 夏季
    return {
      title: "夏季天气提醒",
      content: "贵港夏季(6-9月)气温较高，平均温度在28-35℃，降水较多且湿度大。建议携带遮阳伞、防晒霜(SPF30+)、太阳镜和速干衣物，准备充足饮用水防止中暑。出行前关注天气预报，雷阵雨天气请避免户外活动，特别是山区和水域景点。"
    };
  } else if (month >= 10 && month <= 11) {
    // 秋季
    return {
      title: "秋季天气提醒",
      content: "贵港秋季(10-11月)气候宜人，温度适中，平均温度在18-25℃，是旅游的最佳季节。昼夜温差可达8-10℃，建议携带长袖衣物和薄外套，早晚出行注意保暖。秋季空气湿度适宜，但仍建议做好防晒，携带防晒霜和遮阳帽。"
    };
  } else if (month == 12 || month <= 2) {
    // 冬季
    return {
      title: "冬季天气提醒",
      content: "贵港冬季(12-2月)气温较低但不寒冷，平均温度在10-15℃，偶有寒潮天气温度降至5℃以下。建议携带保暖外套、围巾和帽子，注意分层穿着便于调节体温。冬季空气较为干燥，请多补充水分，可携带润唇膏和护手霜。室内外温差大，注意适时增减衣物。"
    };
  } else {
    // 春季
    return {
      title: "春季天气提醒",
      content: "贵港春季(3-5月)气温回升较快，平均温度在15-25℃，雨水较多且天气多变。建议携带轻便雨衣或雨伞，穿着透气防水的鞋子，准备轻薄外套应对温差变化。春季是花粉过敏高发期，过敏体质游客可携带抗过敏药物，户外游览时做好防护。"
    };
  }
};

// 根据游玩天数生成交通建议
const generateTransportationNote = (days, peopleCount) => {
  let content = "贵港市区内可使用打车软件(滴滴)或公交出行，主要景点间距离适中。";
  
  if (days >= 3) {
    content += " 行程超过3天，建议考虑租车自驾，更加灵活便捷，可前往周边县市景点。城区停车位较紧张，请提前了解景点附近停车场信息。";
  } else {
    content += " 短途行程建议使用公共交通工具，经济环保且避免停车问题。市区公交覆盖面广，单程票价1-2元，出行前可下载本地交通APP查询路线。";
  }
  
  if (peopleCount >= 4) {
    content += " 您的出行人数较多，可考虑包车服务或拼车，提前预订会有优惠，节省等待时间。";
  }
  
  content += " 前往郊区景点时建议提前确认返程交通，避免耽误行程。晚间出行注意安全，最好选择正规交通工具。";
  
  return {
    title: "交通出行建议",
    content: content
  };
};

// 根据预算生成美食建议
const generateFoodNote = (budget) => {
  let content = "贵港美食种类丰富，特色小吃包括：";
  
  // 共同的美食推荐
  const commonFood = "粉利、老友粉、酿豆腐、炸螺、烤乳猪、五色糯米饭等地方特色。";
  
  if (budget === 'ultra_economy') {
    content += commonFood + " 建议前往当地小吃街、夜市和平价餐厅就餐，人均20-50元即可享用地道美食。市区多个农贸市场有现做早点，价格实惠且新鲜。饮食注意卫生，避免生冷食物，不建议在路边无证摊贩处就餐。";
  } else if (budget === 'economy') {
    content += commonFood + " 建议前往当地小吃街、夜市和平价餐厅就餐，人均20-50元即可享用地道美食。市区多个农贸市场有现做早点，价格实惠且新鲜。饮食注意卫生，避免生冷食物，不建议在路边无证摊贩处就餐。";
  } else if (budget === 'medium') {
    content += commonFood + " 市区有多家中档餐厅提供正宗本地菜，人均50-100元，推荐品尝本地河鲜和农家土菜。用餐高峰期建议提前预约，或通过美团、饿了么等平台了解人气餐厅。尝试不同区域的特色菜系，体验多样化的贵港美食文化。";
  } else if (budget === 'quality') {
    content += commonFood + " 高端餐厅集中在市中心和高档酒店内，提供精致本地菜和各地名菜，人均100-300元。推荐尝试创新融合菜和特色宴席，如'贵港八大碗'。部分高级餐厅需提前1-2天预约，可安排私人定制菜单。品尝名贵食材如野生河鱼和农家土鸡，感受真正的贵港味道。";
  } else { // luxury
    content += commonFood + " 高端餐厅集中在市中心和高档酒店内，提供精致本地菜和各地名菜，人均100-300元。推荐尝试创新融合菜和特色宴席，如'贵港八大碗'。部分高级餐厅需提前1-2天预约，可安排私人定制菜单。品尝名贵食材如野生河鱼和农家土鸡，感受真正的贵港味道。";
  }
  
  return {
    title: "美食攻略",
    content: content
  };
};

// 根据特殊需求生成相应建议
const generateCustomizedNotes = (requirements, days, remarks) => {
  const notes = [];
  
  // 针对摄影爱好者
  if (requirements.includes('photo')) {
    notes.push({
      title: "摄影指南",
      content: "贵港江滨和古建筑在早晨(7:00-9:00)和黄昏(17:00-18:30)光线最佳，城市夜景拍摄推荐江滨公园观景台。携带广角镜头捕捉全景，微距镜头拍摄特色美食和工艺品细节。三脚架对夜景和长曝光拍摄必不可少，建议携带快门线和备用电池。雨后的古镇和公园光线柔和，是摄影的绝佳时机。拍摄当地人物肖像请事先征得同意，尊重当地居民隐私。"
    });
  }
  
  // 针对美食爱好者
  if (requirements.includes('food')) {
    notes.push({
      title: "美食探索指南",
      content: "建议每天预留1-2小时探访当地小吃，贵港美食街集中了地道小吃，上午9:00-11:00人较少。品尝地方特色如粉利、螺蛳粉、酿豆腐时，可以根据个人口味调节辣度。传统早点摊位多在6:30-9:00营业，尝试米粉、肠粉和豆浆油条。好的餐厅用餐高峰为12:00-13:30和18:00-19:30，建议错峰就餐。在当地餐厅点菜时，向服务员询问当季特色菜品和招牌菜，体验最地道的味道。准备一些常备药品，应对可能的水土不服。"
    });
  }
  
  // 针对文化体验
  if (requirements.includes('culture')) {
    notes.push({
      title: "文化体验指南",
      content: "贵港历史文化底蕴深厚，博物馆通常在周一闭馆，其他日期9:00-17:00开放(最晚入馆时间16:30)。参观博物馆和文化场所建议提前查询是否需要预约。古镇和传统街区建议安排半天时间慢慢游览，可寻找当地文化讲解员深入了解历史背景。传统手工艺体验如制陶、绣花等需提前1天预约，部分活动需额外付费。当地特色表演如山歌、戏曲多在周末和节假日举行，可咨询酒店前台了解具体时间。尊重当地风俗习惯，拍照前询问是否允许，特别是在宗教场所。"
    });
  }
  
  // 针对亲子活动
  if (requirements.includes('family')) {
    notes.push({
      title: "亲子游玩提示",
      content: "带孩子游玩贵港，建议行程安排不宜过满，每天保留充足休息时间。部分景点有专门的儿童区域和互动项目，让孩子参与其中增加趣味性。携带防晒霜(儿童专用SPF30+)、驱蚊液、湿巾和常备药品(感冒药、退烧药、创可贴等)。准备零食、水和孩子喜欢的玩具，在排队或交通途中缓解焦躁。贵港公园和室外景点设施简单，可自备简易游戏道具增加互动。注意景点人流情况，避免高峰时段参观，防止走失。餐厅就餐时可提前告知服务员准备儿童餐具或调整口味。"
    });
  }
  
  // 针对多天旅行的行李打包建议
  if (days >= 3) {
    notes.push({
      title: "行李打包建议",
      content: "行程超过3天，建议携带轻便行李，选择易干易洗的衣物。必备物品包括：身份证件和复印件、现金和银行卡、充电器和充电宝、常用药品(退烧药、止泻药、创可贴等)。根据季节准备适当衣物，夏季需防晒用品和遮阳帽，冬季需保暖外套和围巾。摄影爱好者准备相机设备和存储卡，记得防雨防尘保护。贵港住宿多提供基础洗漱用品，但建议自备牙刷、牙膏和个人护肤品。长时间户外活动准备便携式折叠伞、水壶和小型急救包。贵重物品随身携带，不要放在托运行李中。"
    });
  }
  
  // 根据用户备注生成个性化建议
  if (remarks) {
    notes.push({
      title: "个性化建议",
      content: `根据您的需求"${remarks}"，我们建议：${generatePersonalizedTips(remarks)}`
    });
  }
  
  return notes;
};

// 生成所有注意事项
const generateAllNotes = (formData, selectedSpots) => {
  const { days, date, people, budget, requirements, remarks } = formData;
  
  // 基础注意事项
  const baseNotes = [
    generateWeatherNote(date),
    generateTransportationNote(days, people),
    generateFoodNote(budget),
    {
      title: "预订提醒",
      content: "旺季出行(暑假7-8月、国庆10月、春节期间)建议提前15-30天预订酒店和热门景点门票，避免现场排队或无票。周末和节假日景点客流量大增，建议错峰出行。部分景区和博物馆实行网络实名预约制，请提前在官方平台或第三方旅游APP预约。贵港高星级酒店在会展或节假日期间房价上浮明显，建议避开高峰期。景区门票多有优惠政策，如学生证、老年证等可享受折扣，出行前查询清楚。"
    }
  ];
  
  // 特殊需求相关注意事项
  const customNotes = generateCustomizedNotes(requirements, days, remarks);
  
  // 安全提示
  const safetyNote = {
    title: "安全提示",
    content: "贵港整体治安良好，但仍需注意人身和财产安全。贵重物品和证件妥善保管，不要放在外衣口袋或背包外侧。游览拥挤景点时提防小偷，景区游玩时不要脱离团队或独自前往偏僻区域。保存好导游或领队联系方式和酒店地址。夜间出行尽量结伴而行，避免单独前往偏僻地区。饮食卫生方面，生冷食物慎重食用，瓜果需充分清洗。游玩水域景点时遵守安全警示，不要擅自下水，遇到险情立即求助工作人员。"
  };
  
  // 紧急联系方式
  const emergencyNote = {
    title: "紧急联系方式",
    content: "旅行期间请保存以下紧急联系方式：报警电话110、急救电话120、火警电话119、旅游投诉电话12301。贵港市人民医院24小时急诊电话：0775-4200120。入住酒店后记录前台电话和房间号码。建议购买旅游意外保险，为行程提供基本保障。创建一个旅行群组，添加所有同行人员，便于沟通和紧急情况联系。"
  };
  
  return [...baseNotes, ...customNotes, safetyNote, emergencyNote];
};

// 保存攻略
const saveGuide = () => {
  ElMessage.success("攻略已保存");
};

// 分享攻略
const shareGuide = () => {
  ElMessage.success("分享链接已复制到剪贴板");
};

// 根据ID获取景点名称
const getSpotNameById = (spotId) => {
  const spot = spots.value.find(s => s.value === spotId);
  return spot ? spot.label : '未知景点';
};

// 移除已选景点
const removeSelectedSpot = (spotId) => {
  const index = form.spots.indexOf(spotId);
  if (index !== -1) {
    form.spots.splice(index, 1);
  }
};

// 获取景点推荐
const getSpotsRecommendation = () => {
  if (form.spots.length === 0 || spots.value.length <= 5) return [];
  
  // 已选择的景点类别分析
  const selectedSpots = spots.value.filter(s => form.spots.includes(s.value));
  
  // 未选择的景点
  const unselectedSpots = spots.value.filter(s => !form.spots.includes(s.value));
  if (unselectedSpots.length === 0) return [];
  
  // 基于关键词匹配进行推荐
  let recommendations = [];
  
  // 提取已选景点的关键词
  const selectedKeywords = [];
  selectedSpots.forEach(spot => {
    const label = spot.label.toLowerCase();
    const desc = spot.description.toLowerCase();
    
    // 提取关键词
    ['博物馆', '公园', '古镇', '文化', '美食', '寺庙', '园', '山'].forEach(keyword => {
      if (label.includes(keyword) || desc.includes(keyword)) {
        selectedKeywords.push(keyword);
      }
    });
  });
  
  // 基于关键词匹配推荐
  if (selectedKeywords.length > 0) {
    unselectedSpots.forEach(spot => {
      const label = spot.label.toLowerCase();
      const desc = spot.description.toLowerCase();
      
      // 检查是否包含任何关键词
      const matchedKeywords = selectedKeywords.filter(keyword => 
        label.includes(keyword) || desc.includes(keyword)
      );
      
      if (matchedKeywords.length > 0) {
        recommendations.push({
          ...spot,
          relevance: matchedKeywords.length // 相关性得分
        });
      }
    });
  }
  
  // 如果基于关键词没有足够推荐，添加随机推荐
  if (recommendations.length < 3) {
    // 随机选择未推荐的景点
    const remainingSpots = unselectedSpots.filter(
      s => !recommendations.some(r => r.value === s.value)
    );
    
    // 随机打乱
    const shuffled = [...remainingSpots].sort(() => 0.5 - Math.random());
    
    // 添加到推荐中
    recommendations = [...recommendations, ...shuffled.slice(0, 3 - recommendations.length)];
  }
  
  // 按相关性排序并限制数量
  return recommendations
    .sort((a, b) => (b.relevance || 0) - (a.relevance || 0))
    .slice(0, 3);
};

// 添加推荐的景点
const addRecommendedSpot = (spotId) => {
  if (!form.spots.includes(spotId)) {
    form.spots.push(spotId);
    ElMessage.success(`已添加到行程`);
  }
};

// 获取总预算
const getTotalBudget = () => {
  if (!generatedGuide.value || !generatedGuide.value.budget) return 0;
  // 此函数返回的是总预算，已经包含了所有人的费用
  return generatedGuide.value.budget.reduce((sum, item) => sum + item.amount, 0);
};

// 获取预算类型文本
const getBudgetTypeText = () => {
  switch (form.budget) {
    case 'ultra_economy':
      return '超值型';
    case 'economy':
      return '经济型';
    case 'medium':
      return '舒适型';
    case 'quality':
      return '品质型';
    case 'luxury':
      return '豪华型';
    case 'premium':
      return '尊享型';
    default:
      return '标准型';
  }
};

// 获取AI评价
const getAIEvaluation = () => {
  const spotsCount = form.spots.length;
  const daysCount = form.days;
  
  // 计算景点和天数的比例
  const ratio = spotsCount / daysCount;
  
  if (ratio < 1) {
    return `景点数量较少，行程相对轻松，适合深度体验每个景点。建议适当增加景点或体验项目，充分利用旅游时间。`;
  } else if (ratio >= 1 && ratio <= 2) {
    return `规划非常合理，每天游览1-2个主要景点，行程节奏舒适，有充足时间深入体验每个景点的特色和文化内涵。`;
  } else if (ratio > 2 && ratio <= 3) {
    return `行程相对紧凑，每天游览的景点较多，适合想要在有限时间内体验更多景点的游客。建议合理安排游览时间，适当调整游览节奏。`;
  } else {
    return `行程安排较为紧张，平均每天需要游览${Math.round(ratio)}个景点。如果您精力充沛且追求高效游览，这份攻略很适合，但也要注意劳逸结合，避免过度疲劳影响旅行体验。`;
  }
};

// 获取景点分布评价
const getSpotDistributionEvaluation = () => {
  const spotsCount = form.spots.length;
  const selectedSpots = spots.value.filter(spot => form.spots.includes(spot.value));
  const types = {};
  
  // 分析选择的景点类型
  selectedSpots.forEach(spot => {
    // 根据名称判断类型
    let type = '其他';
    if (spot.label.includes('博物馆') || spot.label.includes('纪念馆')) {
      type = '文化历史';
    } else if (spot.label.includes('公园') || spot.label.includes('山') || spot.label.includes('湖')) {
      type = '自然风光';
    } else if (spot.label.includes('街') || spot.label.includes('广场') || spot.label.includes('城')) {
      type = '城市景观';
    } else if (spot.label.includes('美食') || spot.label.includes('商场') || spot.label.includes('市场')) {
      type = '休闲购物';
    }
    
    types[type] = (types[type] || 0) + 1;
  });
  
  const typeCount = Object.keys(types).length;
  
  if (typeCount >= 3) {
    return `您选择的景点类型多样化，涵盖了${Object.keys(types).join('、')}等不同类型，行程丰富多彩，能够全面体验贵港的各种特色。`;
  } else if (typeCount === 2) {
    return `您选择的景点主要集中在${Object.keys(types).join('和')}两类，行程侧重点明确，体验较为集中。`;
  } else {
    const mainType = Object.keys(types)[0];
    return `您选择的景点比较集中，主要是${mainType}类型，适合对此类景点有特别兴趣的游客，但可能错过其他类型的体验。`;
  }
};

// 获取行程节奏评价
const getTravelPaceEvaluation = () => {
  const spotsCount = form.spots.length;
  const days = form.days;
  const ratio = spotsCount / days;
  
  if (ratio < 1.5) {
    return `行程非常轻松，平均每天游览不到2个景点，有充足时间慢慢体验和休息，适合度假式旅行和深度游，老人和孩子也能轻松应对。`;
  } else if (ratio >= 1.5 && ratio <= 2.5) {
    return `行程节奏适中，平均每天游览2-3个景点，既能充分体验各个景点，又不会太过疲劳，是大多数游客的理想选择。`;
  } else if (ratio > 2.5 && ratio <= 4) {
    return `行程节奏较快，平均每天游览3-4个景点，需要较好的体力和合理的时间规划，适合时间有限但想多看景点的游客。`;
  } else {
    return `行程安排非常紧凑，平均每天游览超过4个景点，可能会比较赶，建议适当调整期望，选择最想去的景点深入游览，避免走马观花。`;
  }
};

// 获取预算类型对应的酒店等级
const getBudgetAccommodationLevel = (budgetType) => {
  switch (budgetType) {
    case 'ultra_economy':
      return '经济型连锁酒店或青年旅社';
    case 'economy':
      return '二星级舒适型酒店或精选民宿';
    case 'medium':
      return '三星级舒适型酒店或特色民宿';
    case 'quality':
      return '四星级商务酒店或精品酒店';
    case 'luxury':
      return '四星至五星级豪华酒店';
    case 'premium':
      return '五星级豪华酒店套房或度假村';
    default:
      return '三星级舒适型酒店';
  }
};

// 获取预算评估
const getBudgetEvaluation = () => {
  const budget = form.budget;
  const days = form.days;
  const people = form.people;
  
  let budgetType = '';
  let perPersonTotal = getBudgetPerPerson();
  
  switch (budget) {
    case 'ultra_economy':
      budgetType = '超值型';
      break;
    case 'economy':
      budgetType = '经济型';
      break;
    case 'medium':
      budgetType = '舒适型';
      break;
    case 'quality':
      budgetType = '品质型';
      break;
    case 'luxury':
      budgetType = '豪华型';
      break;
    case 'premium':
      budgetType = '尊享型';
      break;
    default:
      budgetType = '标准型';
  }
  
  const totalBudget = perPersonTotal * people;
  
  return `${budgetType}预算适合大多数游客，总费用约${totalBudget}元(${people}人${days}天)，人均${perPersonTotal}元。其中住宿约占30%，餐饮约占25%，交通约占15%，门票和购物约占30%。${getBudgetTips(budget)}`;
};

// 获取预算小贴士
const getBudgetTips = (budget) => {
  switch (budget) {
    case 'ultra_economy':
      return '超值型预算适合精打细算的游客，住宿以青旅、经济型连锁酒店为主，餐饮以小吃街和平价餐厅为主，交通以公共交通为主，购物有限。';
    case 'economy':
      return '经济型预算适合注重性价比的游客，可选择二星或城市快捷酒店，餐饮平衡小吃和大众餐厅，交通以公共交通为主，适当打车，可购买一些当地特产。';
    case 'medium':
      return '舒适型预算适合追求舒适体验的游客，可选择三星级酒店或精品民宿，品尝当地知名餐厅，交通公交和打车结合，可购买品质较好的伴手礼和特产。';
    case 'quality':
      return '品质型预算适合追求品质的游客，可选择四星级酒店，享用当地知名餐厅和高档餐厅，全程打车出行，可购买精品文创和特色商品，提升整体旅行体验。';
    case 'luxury':
      return '豪华型预算适合注重个性化体验的游客，可选择四五星级豪华酒店，预订当地顶级餐厅，包车或专车出行，购买高品质商品和艺术品，体验VIP服务。';
    case 'premium':
      return '尊享型预算适合追求极致旅行体验的游客，可选择五星级酒店套房，享用私厨定制餐饮，专车或豪华SUV接送，购买奢侈品和当地顶级艺术品，享受全方位定制化服务。';
    default:
      return '标准型预算可满足大部分旅行需求，兼顾舒适度和经济性。';
  }
};

// 获取适合人群评价
const getSuitableGroupEvaluation = () => {
  const requirements = form.requirements;
  const ratio = form.spots.length / form.days;
  
  let groups = [];
  
  if (ratio < 2) {
    groups.push('老年人', '带小孩的家庭');
  } else if (ratio > 3) {
    groups.push('年轻人', '体力充沛的游客');
  } else {
    groups.push('各类游客');
  }
  
  if (requirements.includes('photo')) {
    groups.push('摄影爱好者');
  }
  
  if (requirements.includes('food')) {
    groups.push('美食爱好者');
  }
  
  if (requirements.includes('culture')) {
    groups.push('历史文化爱好者');
  }
  
  if (requirements.includes('family')) {
    groups.push('家庭亲子游');
  }
  
  if (groups.length > 3) {
    // 只取前三个最重要的
    groups = groups.slice(0, 3);
  }
  
  return `此行程最适合${groups.join('、')}，能够满足您的特定需求和偏好。`;
};

// 获取景点分布颜色
const getSpotDistributionColor = () => {
  const selectedSpots = spots.value.filter(spot => form.spots.includes(spot.value));
  const types = {};
  
  // 分析选择的景点类型
  selectedSpots.forEach(spot => {
    // 根据名称判断类型
    let type = '其他';
    if (spot.label.includes('博物馆') || spot.label.includes('纪念馆')) {
      type = '文化历史';
    } else if (spot.label.includes('公园') || spot.label.includes('山') || spot.label.includes('湖')) {
      type = '自然风光';
    } else if (spot.label.includes('街') || spot.label.includes('广场') || spot.label.includes('城')) {
      type = '城市景观';
    } else if (spot.label.includes('美食') || spot.label.includes('商场') || spot.label.includes('市场')) {
      type = '休闲购物';
    }
    
    types[type] = (types[type] || 0) + 1;
  });
  
  const typeCount = Object.keys(types).length;
  
  if (typeCount >= 3) return 'bg-green-500';
  if (typeCount === 2) return 'bg-yellow-500';
  return 'bg-orange-500';
};

// 获取行程节奏颜色
const getPaceColor = () => {
  const ratio = form.spots.length / form.days;
  
  if (ratio < 1.5) return 'bg-green-500';
  if (ratio >= 1.5 && ratio <= 3) return 'bg-green-500';
  if (ratio > 3 && ratio <= 4) return 'bg-yellow-500';
  return 'bg-red-500';
};

// 获取AI警告颜色
const getAIWarnColor = () => {
  const spotsCount = form.spots.length;
  const daysCount = form.days;
  const ratio = spotsCount / daysCount;
  
  if (ratio <= 2) return 'green';
  if (ratio <= 3) return 'yellow';
  return 'red';
};

// 获取AI警告文本
const getAIWarnText = () => {
  const spotsCount = form.spots.length;
  const daysCount = form.days;
  const ratio = spotsCount / daysCount;
  
  if (ratio <= 2) return '行程轻松舒适';
  if (ratio <= 3) return '行程适度紧凑';
  return '行程较为紧张';
};

// 页面加载时获取景点数据
onMounted(() => {
  fetchSpots();
  checkApiAvailability();
});

// 新增的反馈逻辑
const feedback = ref('');
const feedbackComment = ref('');

const submitFeedback = (type) => {
  feedback.value = type;
  if (type === 'good' || type === 'neutral') {
    ElMessage.success("感谢您的反馈！");
  }
};

const submitDetailedFeedback = () => {
  // 实际的反馈提交逻辑
  ElMessage.success("感谢您的详细反馈，我们会努力改进！");
  feedback.value = '';
  feedbackComment.value = '';
};

// 获取预算类型对应的餐饮等级
const getBudgetFoodLevel = (budgetType) => {
  switch (budgetType) {
    case 'ultra_economy':
      return '街边小吃、平价餐厅';
    case 'economy':
      return '大众连锁餐厅、当地特色小吃';
    case 'medium':
      return '中档餐厅、知名当地特色餐厅';
    case 'quality':
      return '高档餐厅、特色餐厅、含1-2次精品餐饮体验';
    case 'luxury':
      return '高端餐厅、知名餐厅、含多次特色餐饮体验';
    case 'premium':
      return '顶级餐厅、米其林餐厅、私人定制餐饮';
    default:
      return '中档餐厅、当地特色餐厅';
  }
};

// 获取人均预算金额
const getBudgetPerPerson = () => {
  const budget = form.budget;
  
  switch (budget) {
    case 'ultra_economy':
      return 500;
    case 'economy':
      return 1000;
    case 'medium':
      return 1500;
    case 'quality':
      return 2000;
    case 'luxury':
      return 2500;
    case 'premium':
      return 3000;
    default:
      return 1200;
  }
};

// 获取预算类型对应的酒店等级
</script>

<style lang="scss" scoped>
.ai-guide-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .requirement-card {
    @apply flex flex-col items-center justify-center p-4 rounded-lg border-2 border-gray-200 dark:border-gray-700 cursor-pointer transition-all duration-300;

    &:hover {
      @apply border-primary-500 dark:border-primary-400;
    }

    &.is-active {
      @apply bg-primary-50 dark:bg-primary-900/50 border-primary-500 dark:border-primary-400;
    }
  }

  .timeline-card {
    @apply bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm;
  }

  .time-tag {
    @apply px-2 py-1 bg-primary-50 dark:bg-primary-900/50 text-primary-600 dark:text-primary-400 rounded mr-3;
  }

  .day-number {
    @apply w-8 h-8 rounded-full bg-primary-100 dark:bg-primary-900 text-primary-600 dark:text-primary-400 flex items-center justify-center text-sm mr-3;
  }

  .spot-detail-card {
    @apply bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6;
  }

  .tip-card {
    @apply flex items-center gap-2 p-3 bg-white dark:bg-gray-800 rounded-lg;
  }

  .budget-card {
    @apply bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6 transition-all duration-300;

    &:hover {
      @apply transform -translate-y-1 shadow-md;
    }
  }

  .note-card {
    @apply bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6 transition-all duration-300;

    &:hover {
      @apply transform -translate-y-1 shadow-md;
    }
  }

  .guide-step {
    @apply flex items-start gap-3 p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors;

    .step-number {
      @apply w-6 h-6 rounded-full bg-primary-100 dark:bg-primary-900 text-primary-600 dark:text-primary-400 flex items-center justify-center text-sm font-medium flex-shrink-0;
    }

    .step-content {
      @apply flex-1;

      h4 {
        @apply mb-1;
      }
    }
  }

  :deep(.el-input-number) {
    .el-input-number__decrease,
    .el-input-number__increase {
      @apply bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300;

      &:hover {
        @apply text-primary-500 dark:text-primary-400;
      }
    }

    .el-input__wrapper {
      @apply bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100;
    }
  }
}
</style>
